﻿using System;
using System.Collections.Generic;
using Castle.Core.Configuration;

namespace Inovout.Repositories
{
    [Serializable]
    public class RepositoryConfigurationKeyDictionary : Dictionary<string, string>
    {
        private static string defaultRepositoryDataBaseName;
        private IConfiguration repositoryConfiguration;

        public RepositoryConfigurationKeyDictionary(IConfiguration repositoryConfiguration)
        {
            this.repositoryConfiguration = repositoryConfiguration;
        }
        private readonly string defaultDatabaseKey = "defaultDatabase";
        public void Init(IConfiguration databaseConfiguration)
        {
            ArgumentAssert.IsNotNull(databaseConfiguration, "databaseConfiguration");
            if (repositoryConfiguration == null)
            {
                ArgumentAssert.AreEquals(databaseConfiguration.Children.Count, 1, "repositoryConfiguration");
                repositoryConfiguration = new MutableConfiguration("repositories");
                repositoryConfiguration.Attributes.Add(defaultDatabaseKey, databaseConfiguration.Children[0].Attributes.Get("id"));

            }

            if (repositoryConfiguration.Attributes.Count > 0)
            {
                defaultRepositoryDataBaseName = repositoryConfiguration.Attributes.Get(defaultDatabaseKey);
            }
            foreach (var config in repositoryConfiguration.Children)
            {
                string scope = config.Attributes["Scope"];
                if (string.IsNullOrEmpty(scope))
                {
                    scope = "scope.default";
                }
                string databaseName = config.Attributes["databaseName"];
                base.Add(scope, databaseName);
            }
        }

        public string GetDatabaseName(Type dataObjectType)
        {
            ArgumentAssert.IsNotNull(dataObjectType, "dataObjectType");
            string databaseName;
            if (TryGetValue(dataObjectType.AssemblyQualifiedName, out databaseName))
            {
                return databaseName;
            }
            else
            {
                return defaultRepositoryDataBaseName;
            }
        }
    }
}
